import re
from pathlib import Path
from rich.progress import *
from common.print_and_log import *
from common.web_conn import get_img
from connection.sonic import SonicConn


def main(conn_info, workdir, md_file_path, img_prefix):
    """conn_info:(host,username,password),后两个参数为空值表示不自动上传图片
    md_file_path:md文件的路径
    img_prefix:上传或保存的图片的名称将为img_prefix.png或img_prefix.gif之类"""
    # md文件资源
    md_file_path = Path(workdir, md_file_path)
    md_text = md_file_path.read_text("utf-8")
    new_md_file_path = md_file_path.with_stem(md_file_path.stem + "-modified")
    new_md_text = md_text
    # sonic连接
    host, username, password = conn_info
    auto_upload = username and password
    conn = SonicConn(host)
    # 上传或保存图片需要的资源
    if auto_upload:
        token = conn.get_token("redquilt", "LaPetiteSouris2020")
    else:
        pic_out_dir = Path(workdir, "imgs")
        pic_out_dir.mkdir(parents=True, exist_ok=True)
    # 获取原始url
    img_urls = re.findall(r"!\[.*\]\((.*)\)", md_text)
    img_count = len(img_urls)
    # 警告
    if img_count > 20:
        proceed = input("图片的数量非常多，真的要继续进行吗？[y/n]\n")
        if proceed.lower().strip() == "n":
            return
    # 下载图片
    for i, old_img_url in track(
        enumerate(img_urls, 1),
        "正在下载图片：",
        len(img_urls),
    ):
        new_img_stem = "{}-{:0=2}".format(img_prefix, i)
        img_info = get_img(old_img_url, new_img_stem)
        if img_info:
            # 保存或上传图片
            if auto_upload and token:
                # 把图片上传到Sonic
                conn.upload_mem_attachment(
                    img_info["name"], img_info["content"], img_info["extension"]
                )
            elif not auto_upload:
                # 把图片下载到本地
                Path(pic_out_dir, img_info["name"]).write_bytes(img_info["content"])
            # 替换md字符串
            new_img_url = conn.get_attachment_url_path(img_info["name"])
            new_md_text = new_md_text.replace(old_img_url, new_img_url)
    # 保存新的md文件
    new_md_file_path.write_text(new_md_text, encoding="utf-8")
